import {
    Table,
    Descriptions,
    Button,
    Input,
    Modal,
    Form,
    Radio,
    Select,
    Cascader,
    DatePicker,
    Upload,
    message,
    Space
} from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import React, { useEffect, useState } from 'react';
import { getRestList, getRestCount, foodClass, getRestClass, upDateRest, deleteRest, } from "../../api/request"
import { PlusOutlined, LoadingOutlined, RightOutlined, DownOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const { RangePicker } = DatePicker;
const { TextArea } = Input;

const details: any = (record: any) => (
    <Descriptions column={2} layout="horizontal">
        <Descriptions.Item label="店铺名称">{record.name}</Descriptions.Item>
        <Descriptions.Item label="店铺地址">{record.address}</Descriptions.Item>
        <Descriptions.Item label="店铺介绍">{record.description}</Descriptions.Item>
        <Descriptions.Item label="店铺ID">{record.id}</Descriptions.Item>
        <Descriptions.Item label="联系电话">{record.phone}</Descriptions.Item>
        <Descriptions.Item label="评分">{record.rating}</Descriptions.Item>
        <Descriptions.Item label="销售量">{record.recent_order_num}</Descriptions.Item>
        <Descriptions.Item label="分类">{record.category}</Descriptions.Item>
    </Descriptions>
);



const App: any = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [data, setData] = useState()
    const [count, setCount] = useState()
    //当前页
    const [Page, setPage] = useState(0)
    //每页条数
    const [PageSize, setPageSize] = useState(20)
    //食品分类
    const [foods, setFoods] = useState([])

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const [restId, setRestId] = useState()
    const Navigate = useNavigate()

    const [edit, setEdit] = useState({})
    const [defaultImg, setDefaultImg] = useState("")
    const changeMerchant = (id: any, record: any) => {
        // console.log(1111111111, record);
        // console.log(22222222222222222, record.image_path);
        setEdit(() => {
            return {
                name: record.name,
                address: record.address,
                description: record.description,
                phone: record.phone,
                category: record.category,
            }
        })
        setDefaultImg(record.image_path)

        setIsModalOpen(true);

        setRestId(() => id)
    }
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    };
    const [imgUrl, setImgUrl] = useState()
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.response) {
            setImgUrl(() => info.file.response.image_path)
            console.log(6666, imgUrl);
        }
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done' && info.file.response) {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, url => {
                setLoading(false);
                setImageUrl(() => info.file.response.image_path);
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };


    const onchange = (page: number, pageSize: number) => {
        setPage(() => page * 10)
        setPageSize(() => pageSize)
    }
    const setShopping = (id: any) => {
        localStorage.setItem("restaurant_id", id)
        localStorage.setItem("keypath", "/add,/add/foods")
        Navigate("/add/foods")
        window.location.reload()
    }
    const deleteShop = (id: any) => {
        deleteRest(id).then((res) => {
            message.error(res.message);
        })
    }

    useEffect(() => {
        //获取商家列表信息
        getRestList({ offset: Page, limit: PageSize }).then((res: any) => {
            // console.log(res.data);

            setData(res.data)
        }
        )
        //获取餐馆总数量
        getRestCount().then((res: any) => {
            setCount(res.data.count)
        })
        //获取食品分类
        getRestClass().then((res: any) => {
            // console.log(res.data);
            setFoods(() => res.data.map((value: any) => {
                return {
                    value: value.name,
                    label: value.name,
                    children: value.sub_categories.map((item: any) => {
                        return {
                            value: item.name,
                            label: item.name,
                        }
                    }),
                }
            }))
        })
    }, [PageSize, Page])

    const columns = [
        { title: '店铺名称', dataIndex: 'name', },
        { title: '店铺地址', dataIndex: 'address', },
        { title: '店铺介绍', dataIndex: 'description', },
        {
            title: '操作',
            dataIndex: 'id',

            render: (text: string, record: any) => {
                return (
                    <>
                        <Button onClick={() => changeMerchant(text, record)} size="small" style={{
                            marginRight: "10px",
                            borderRadius: "5px"
                        }}>编辑</Button>
                        <Button onClick={() => setShopping(text)} size="small" style={{
                            marginRight: "10px",
                            borderRadius: "5px"
                        }}>添加食品</Button>
                        <Button onClick={() => deleteShop(text)} size="small" type="primary" style={{
                            marginRight: "10px",
                            borderRadius: "5px"
                        }} danger>
                            删除
                        </Button>
                    </>
                )
            },
        },
    ];

    const handleCancel = () => {
        console.log(1);
        setEdit(() => {
            console.log(2);
            setTimeout(() => {
                return {
                    name: "",
                    address: "",
                    description: "",
                    phone: "",
                    category: ""
                }
            }, 0);
            setTimeout(() => {
                console.log(222222222222222, edit);
            }, 0);

            setIsModalOpen(false);
        })
        window.location.reload()

    };

    const submit = (values: any) => {
        console.log(values);
        const data = {
            ...values,
            id: restId,
            image_path: imageUrl
        }
        upDateRest(data).then((res) => {
            console.log(res);
            if (res.status == 1) {
                message.success(res.success);
                setIsModalOpen(false);
                window.location.reload()
            } else {
                message.error(res.message);
            }
        })
    }
    return (
        <>
            <Table
                columns={columns}
                expandIcon={({ expanded, onExpand, record }) =>
                    expanded ? (
                        <DownOutlined onClick={e => onExpand(record, e)} />
                    ) : (
                        <RightOutlined onClick={e => onExpand(record, e)} />
                    )
                }
                expandable={{
                    expandedRowRender: record => details(record),
                }}

                dataSource={data}
                pagination={{
                    pageSize: PageSize, total: count, onChange: (page, pageSize) => {
                        onchange(page, pageSize)
                    }
                }}
                scroll={{ y: 450 }}
                rowKey={(res: any) => res.id}
            />
            <Modal title="修改店铺信息" open={isModalOpen} onCancel={handleCancel} footer={null}>
                <Form
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 14 }}
                    layout="horizontal"
                    onFinish={submit}
                    requiredMark={true}
                    scrollToFirstError={isModalOpen}
                    initialValues={edit}


                // onValuesChange={onFormLayoutChange}
                // disabled={componentDisabled}
                >
                    <Form.Item rules={[{ required: true }]} label="店铺名称" name="name" >
                        <Input />
                    </Form.Item>
                    <Form.Item rules={[{ required: true }]} label="详细地址" name="address" >
                        <Input placeholder='请输入地址' />
                    </Form.Item>
                    <Form.Item rules={[{ required: true }]} label="店铺介绍" name="description" >
                        <Input />
                    </Form.Item>
                    <Form.Item rules={[{ required: true }]} label="联系电话" name="phone" >
                        <Input />
                    </Form.Item>
                    <Form.Item rules={[{ required: true }]} label="店铺分类" name="category" >
                        <Cascader
                            options={foods}
                        />
                    </Form.Item>

                    <Form.Item label="店铺图片" valuePropName="fileList">
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="/v1/addimg/shop"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            <img src={imageUrl ? '//elm.cangdu.org/img/' + imageUrl : '//elm.cangdu.org/img/' + defaultImg} alt="avatar" style={{ width: 120, height: 100 }} />
                        </Upload>
                    </Form.Item>
                    <Form.Item>
                        <Button style={{
                            marginLeft: 80
                        }} type="primary" htmlType="submit">提交</Button>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );

}

export default App;